package com.yungu.swift.socket.communication.server.handler.strategy;

import com.google.gson.Gson;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.lbs.model.DriverPoint;
import com.yungu.swift.lbs.service.LocationService;
import com.yungu.swift.socket.communication.message.GetDriverLocationMessage;
import com.yungu.swift.socket.communication.message.GetLocationResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 获取司机位置响应
 *
 * @author : cuixiuyin
 * @date : 2019/8/30
 */
public class DriverLocationHandler implements MessageHandler {


    @Override
    public void handler(ChannelHandlerContext channelHandlerContext, String text) {
        LocationService locationService = SpringContextHolder.getBean(LocationService.class);
        Gson gson = new Gson();
        //将报文转换成可保存的实体
        GetDriverLocationMessage getDriverLocationMessage = gson.fromJson(text, GetDriverLocationMessage.class);
        //处理业务逻辑
        ResponseData<DriverPoint> responseData = locationService.findDriverPoint(
                getDriverLocationMessage.getDriverUuid(), getDriverLocationMessage.getAppid());
        DriverPoint driverPoint = responseData.getData();
        GetLocationResponseMessage getLocationResponseMessage;
        if (driverPoint == null) {
            getLocationResponseMessage = new GetLocationResponseMessage(getDriverLocationMessage.getDriverUuid(), 0D, 0D, false, "获取失败");
        } else {
            getLocationResponseMessage = new GetLocationResponseMessage(getDriverLocationMessage.getDriverUuid(), driverPoint.getCoordinate().getLng(), driverPoint.getCoordinate().getLat(), true, "获取成功");

        }//给响应客户端响应处理结果
        getLocationResponseMessage.setClientUuid(getDriverLocationMessage.getClientUuid());
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(gson.toJson(getLocationResponseMessage)));
    }
}
